<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 商户提现
 * Class MerchantCash
 * @author heyu
 */
class MerchantCash extends MY_Controller {
    /**
     * @var MerchantBalanceModel
     */
    public $mBalance;

	public function __construct(){
		parent::__construct();
		$this->loadModel('MerchantBalanceModel', 'mBalance', 'merchant');
	}

	/**
	 * 首页
	 */
	public function index(){
	    $config = $this->mBalance->config;
		$data = array(
			'title' =>'商户提现',
			'status' => $config['status'],
		);
		$this->view('fund/merchantCash',$data,'datatable,validation,datepicker');
	}

	/**
	 * 列表
	 */
	public function getList(){
	    $_GET['found_type'] = 4;
        $config = $this->mBalance->config;
        $data = $this->mBalance->adminGetList();
        if(!empty($data['data'])){
            foreach ($data['data'] as $k =>$v){
                $data['aaData'][$k][] = $v['id'];
                $data['aaData'][$k][] = $v['shop_name'];
                $data['aaData'][$k][] = $config['pay_type'][$v['pay_type']];
                $data['aaData'][$k][] = $v['amount'];
                $data['aaData'][$k][] = isset($v['confirm_time']) ? dateFormat($v['confirm_time']) : '';
                $data['aaData'][$k][] = dateFormat($v['addtime']);
                if ($v['status'] == 1){
                    $data['aaData'][$k][] = '<a href="#" class="popovers" data-placement="left" data-trigger="hover" data-content="'.
                        $v['reason'].'" data-original-title="拒绝原因">'.$this->getStatus($v['status'],true).'</a>';
                }else{
                    $data['aaData'][$k][] = $this->getStatus($v['status'],true);
                }
                if ($v['status'] == 3) {
                    $btnConfig = adminCreateBtn(array(
                        'label' => ' 已打款',
                        'icon' => '',
                        'attr' => array(
                            'href' => getUrl('fund/merchantCash/changeStatus') . '?id=' . $v['id'] . '&status=2',
                            'class' => 'ajax-request-btn btn default btn-xs blue-stripe',
                            'alert-message' => "确认要标记为已打款吗？"
                        ),
                        'tag' => 'a',
                        'permissions' => array(
                            'module' => 'fund',
                            'key' => 'merchantCash-status'
                        )
                    ));
                    $btnConfig .= ' ' . adminCreateBtn(array(
                            'label' => ' 拒绝',
                            'icon' => '',
                            'attr' => array(
                                'href' => 'javascript:;',
                                'class' => 'btn default btn-xs red-stripe edit-btn',
                                'data-id' => $v['id'],
                            ),
                            'tag' => 'a',
                            'permissions' => array(
                                'module' => 'fund',
                                'key' => 'merchantCash-status'
                            )
                        ));
                }else{
                    $btnConfig = '';
                }
                $data['aaData'][$k][] = $btnConfig;
            }
        }
        unset($data['data']);
        echo json_encode($data);
	}

    /**
     * 获取状态
     *
     * @param	integer	$key
     * @param	boolean	$show	是否显示
     * @return	mixed
     */
    public function getStatus($key = null, $show = false){

        $config = array(
            '1' => '失败',
            '2' => '成功',
            '3' => '申请中'
        );

        if($key !== null){

            if(isset($config[$key]) && ! $show){
                return $config[$key];
            }

            if(isset($config[$key]) && $show){

                if($key == 1){
                    return '<span class="label label-danger">'.$config[$key].'</span>';
                }else if($key == 2){
                    return '<span class="label label-success">'.$config[$key].'</span>';
                }else if($key == 3){
                    return '<span class="label label-warning">'.$config[$key].'</span>';
                }
            }
            return '';
        }

        return $config;
    }

    /**
     * 修改状态
     */
    public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
            array('status', '状态', 'required|is_list[1,2]'),
        );
        $status = (int)get('status');
        if ($status == 1){
            $vConf[] = array('reason', '拒绝理由', 'required');
        }
        $this->formDataValidation($vConf, array(
            'id' => get('id'),
            'status' => get('status'),
            'reason' => get('reason')
        ));
        $id = get('id');
        $info = $this->mBalance->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }
        if ($info['status'] != 3){
            $this->ajaxReturn(0, '不能修改此状态');
        }
        $data = array('status' => $status,'confirm_time' => time());
        $this->db->trans_begin();
        if ($status == 1){
            // 退款余额到商户账户
            $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
            $merchant = $this->mMerchant->getInfo($info['merchant_id']);
            if (!$merchant){
                $this->ajaxReturn(0, '商户信息不存在');
            }
            $amount = ltrim($info['amount'], '-');
            $balance = $merchant['balance']+(int)$amount;
            $mer = $this->mMerchant->save(array('balance'=> $balance), $info['merchant_id']);
            if (!$mer){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '退款金额失败');
            }
            $data['reason'] = trim(get('reason'));
        }
        if(!$this->mBalance->save($data, $id)){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $this->db->trans_commit();
        $this->ajaxReturn(1, '已保存');
    }

    /**
     * 导出
     */
    public function export(){
        $filename = '商户提现'.date('Y-m-d',time()).'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('商户,提现方式,金额,完成时间,添加时间,状态','gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;
        $config = $this->mBalance->config;
        $_GET['found_type'] = 4;
        while(true){
            $data =$this->mBalance->adminGetList(array(), array('page' => $page, 'pageNumber' => $pageNumber));
            if(empty($data)){
                break;
            }
            $page ++;
            foreach($data as $v){
                $confirmTime = isset($v['confirm_time']) ? dateFormat($v['confirm_time']) : '';
                $addtime = dateFormat($v['addtime']);
                $status = $this->getStatus($v['status']);
                echo mb_convert_encoding($v['shop_name'].','.$config['pay_type'][$v['pay_type']].','.$v['amount'].','.$confirmTime.','.$addtime.','.$status, 'gb2312','utf-8')."\n";
            }
        }
    }
}
